#include "XWindow.ph"
#ifdef __GNUG__
#pragma implementation
#endif

#include "XColorMap.h"

#include "Math.h"
#include "Env.h"
#include "XWinSystem.h"
#include "XWindowPort.h"
#include "ET_stdio.h"

//---- XColorIndexMapper -------------------------------------------------------

XColorIndexMapper::XColorIndexMapper(XColormap cm, bool readwrite)
						: WindowIndexMapper(readwrite)
{
	cmap= cm;
	length= MAXREDS*MAXGREENS*MAXBLUES;
}

XColorIndexMapper::XColorIndexMapper(XColorIndexMapper *from)
						: WindowIndexMapper(from)
{
	// cmap= XCopyColormapAndFree(XWinSystem::display, from->cmap);
	cmap= from->cmap;
}

WindowColorMap *XColorIndexMapper::DevMakeCopy(WindowColorMap *from)
{
	return new XColorIndexMapper((XColorIndexMapper*)from);
}

u_long XColorIndexMapper::DevRGB2Index2(RGB *rgb)
{
	XColor xc0;

	xc0.red= rgb->red * 257;
	xc0.green= rgb->green * 257;
	xc0.blue= rgb->blue * 257;

	xc0.flags= DoRed | DoGreen | DoBlue;
	XAllocColor(XWinSystem::display, cmap, &xc0);

	realmap[xc0.pixel].red= xc0.red / 257;
	realmap[xc0.pixel].green= xc0.green / 257;
	realmap[xc0.pixel].blue= xc0.blue / 257;

	return (u_long) xc0.pixel;
}

void XColorIndexMapper::DevInstall(Port*)
{
	XStoreColors(XWinSystem::display, cmap, xc, changed);
	changed= 0;
}

u_long XColorIndexMapper::DevAllocateAndSetCell(long xid, RGB *rgb, WindowPort *p)
{
	if (xid < 0) {
		XWindowPort *xport= (XWindowPort*) p;
		u_long planemask[1], pixels[1];
		if (XAllocColorCells(XWinSystem::display, cmap, XFalse, planemask, 0, pixels, 1) == 0) {
			fprintf(stderr, "can't get new color\n");
			cmap= XCreateColormap(XWinSystem::display, xport->winid, XWinSystem::dfltvisual, AllocNone);
			// cmap= XCopyColormapAndFree(XWinSystem::display, cmap);
			XSetWindowColormap(XWinSystem::display, xport->winid, cmap);
			if (XAllocColorCells(XWinSystem::display, cmap, XFalse, planemask, 0, pixels, 1) == 0) {
				fprintf(stderr, "can't get new color 2\n");
			}
		}
		xid= pixels[0];
	}

	XColor *x= &xc[changed++];
	x->red= rgb->red * 257;
	x->green= rgb->green * 257;
	x->blue= rgb->blue * 257;
	x->flags= DoRed | DoGreen | DoBlue;
	x->pixel= xid;

	realmap[xid]= *rgb;

	return xid;
}

